package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import SqlJavaBean.RunSql;
import SqlJavaBean.User;

import java.io.PrintWriter;
import java.sql.Connection;

import t.DBBean;

/**
 * Servlet implementation class servlet
 */
@WebServlet("/server.view")
public class server extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public server() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		String android = request.getParameter("android");
		PrintWriter out = response.getWriter();
		if(android!=null && android!=""){
			out.print(doAndroid(request));
			return;
		}
		HttpSession s =  request.getSession();
		Connection con = (Connection)s.getAttribute("con");
		if(con==null) {
			out.print("请登录后再使用本服务！");
			return;
		}
		String sql = request.getParameter("sql");
		RunSql run = new RunSql(con);
		String res = run.runSql(sql);
		out.print(res);
		
		
	}
	
	private String doAndroid(HttpServletRequest request){
		String user = request.getParameter("user");
		String passwd = request.getParameter("passwd");
		String sql = request.getParameter("sql");
		User u = new User();
		Connection con = u.userLogin(user, passwd);
		if(con==null) return "请先登录再使用本功能!user="+user+"%%%passwd="+passwd;
		RunSql run = new RunSql(con);
		return run.runSql(sql);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
